package com.ck567.practice.reflex.reflexModle;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author wuhao
 * @date 2021/1/8 10:32
 */
public class ReflexTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
        //根据全路径类名拿到对应的class对象
        Class re = Class.forName("com.ck567.practice.reflex.reflexModle.ReflexModle");
        System.out.println(re.getCanonicalName());
        //将class类对象实例化，拿到
        ReflexModle reflexModle = (ReflexModle)re.newInstance();
        //拿到名为ReflexModle类中的publicMethod方法 getMethod()用于获取对象的公共方法
        Method publicMethod = re.getMethod("publicMethod");
        publicMethod.setAccessible(true);
        Object str1 = publicMethod.invoke(reflexModle);
        System.out.println(str1);

        //拿到名为ReflexModle类中的privateMethod方法 getDeclaredMethod()用于获取对象的私有方法
        Method privateMethod = re.getDeclaredMethod("privateMethod");
        privateMethod.setAccessible(true);
        Object str2 = privateMethod.invoke(reflexModle);
        System.out.println(str2);


        //拿到名为ReflexModle类中的reflexinterf方法
        //getDeclaredMethod()、getMethod()都可以用于获取对象实现的方法
        Method reflexinterf = re.getMethod("reflexinterf");
        reflexinterf.setAccessible(true);
        Object str3 = reflexinterf.invoke(reflexModle);
        System.out.println(str3);


        //调用父类的public方法
        Method myMoney = re.getMethod("myMoney");
        myMoney.setAccessible(true);
        Object str4 = myMoney.invoke(reflexModle);
        System.out.println(str4);

        //无法直接获取父类的私有方法 报错java.lang.NoSuchMethodException
//        Method myTrousers = re.getDeclaredMethod("myTrousers");
//        myTrousers.setAccessible(true);
//        Object str5 = myTrousers.invoke(reflexModle);
//        System.out.println(str5);

        //获取父类的私有方法
        Class superclass = re.getSuperclass();
        Method myTrousers = superclass.getDeclaredMethod("myTrousers");
        myTrousers.setAccessible(true);
        Object str5 = myTrousers.invoke(reflexModle);
        System.out.println(str5);

        //获取属性
        Field field = re.getDeclaredField("name");
        field.setAccessible(true);
        field.set(re,"wwwh");
        System.out.println();
    }
}
